package com.example.Words.room.ui.Fragment;


import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SearchEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.SearchView;

import com.example.Words.R;
import com.example.Words.room.model.entity.Word;
import com.example.Words.room.presenter.RoomPresenterImp;
import com.example.Words.room.presenter.RoomPresenterIntf;
import com.example.Words.room.ui.Adapter.RoomViewAdapter;
import com.example.Words.room.ui.view.RoomIntf;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;

public class WordsFragment extends Fragment implements RoomIntf {
    private RoomPresenterIntf presenterIntf;
    private RoomViewAdapter myadapter;
    private RoomViewAdapter myadapterUseCard;
    private View view;
    private LiveData<List<Word>> filteredWords;
    private static final String VIEW_TYPE_SHP="store_user_preference";
    private static final String IS_USING_CARD_VIEW="use_CardView";
    private boolean undoAction=false;
    private DividerItemDecoration dividerItemDecoration;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    private List<Word> allWords;

    @OnClick(R.id.floatingActionButton)
    void onClick(View v) {
        NavController navController = Navigation.findNavController(v);
        navController.navigate(R.id.action_wordsFragment_to_addFragment);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_words, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ButterKnife.bind(this, view);
        presenterIntf = new RoomPresenterImp(this, requireActivity().getApplication());
        myadapter = new RoomViewAdapter(false, presenterIntf);
        myadapterUseCard = new RoomViewAdapter(true, presenterIntf);
        dividerItemDecoration=new DividerItemDecoration(getActivity(),DividerItemDecoration.VERTICAL);
        recyclerView.setLayoutManager(new LinearLayoutManager(requireActivity()));
        recyclerView.setItemAnimator(new DefaultItemAnimator(){
            @Override
            public void onAnimationFinished(@NonNull RecyclerView.ViewHolder viewHolder) {
                super.onAnimationFinished(viewHolder);
                LinearLayoutManager linearLayoutManager=(LinearLayoutManager) recyclerView.getLayoutManager();
                if (linearLayoutManager!=null){
                int frist=linearLayoutManager.findFirstVisibleItemPosition();
                int last=linearLayoutManager.findLastVisibleItemPosition();
                for(int i=frist;i<=last;i++){
                    RoomViewAdapter.MyViewHolder holder=(RoomViewAdapter.MyViewHolder)recyclerView.findViewHolderForAdapterPosition(i);
                    if(holder!=null){
                        holder.numbertv.setText(String.valueOf(i+1));
                    }
                }
                }
            }
        });
        SharedPreferences sharedPreferences=requireActivity().getSharedPreferences(VIEW_TYPE_SHP, Context.MODE_PRIVATE);
        boolean viewType= sharedPreferences.getBoolean(IS_USING_CARD_VIEW,false);
        if(viewType)
        recyclerView.setAdapter(myadapterUseCard);
        else { recyclerView.setAdapter(myadapter);recyclerView.addItemDecoration(dividerItemDecoration);}
        filteredWords = presenterIntf.getAllWordsLive();
        filteredWords.observe(getViewLifecycleOwner(), new Observer<List<Word>>() {
            @Override
            public void onChanged(List<Word> words) {
                int temp = myadapter.getItemCount();
                allWords=words;
                if (temp != words.size()) {
                    if (temp<words.size()&&!undoAction)
                    recyclerView.smoothScrollBy(0,-200);
                    undoAction=false;
                    myadapter.submitList(words);
                    myadapterUseCard.submitList(words);
                }
            }
        });

        new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP|ItemTouchHelper.DOWN,ItemTouchHelper.START | ItemTouchHelper.END) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                Word wordFrom=allWords.get(viewHolder.getAdapterPosition());
                Word wordTo=allWords.get(target.getAdapterPosition());
                int idTemp=wordFrom.getId();
                wordFrom.setId(wordTo.getId());
                wordTo.setId(idTemp);
                presenterIntf.update(wordFrom,wordTo);
                myadapter.notifyItemMoved(viewHolder.getAdapterPosition(),target.getAdapterPosition());
                myadapterUseCard.notifyItemMoved(viewHolder.getAdapterPosition(),target.getAdapterPosition());
                return false;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                Word word=allWords.get(viewHolder.getAdapterPosition());
                presenterIntf.deleteWords(word);
                Snackbar.make(requireActivity().findViewById(R.id.wordsFragmentView),"删除了一个词汇",Snackbar.LENGTH_SHORT)
                        .setAction("撤销",new View.OnClickListener(){
                            @Override
                            public void onClick(View v) {
                                undoAction=true;
                                presenterIntf.insertDate(word);
                            }
                        }).show();
            }
        }).attachToRecyclerView(recyclerView);
    }

    @Override
    public void changeLayout() {
        myadapter.notifyDataSetChanged();
        myadapterUseCard.notifyDataSetChanged();
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.clearData:
                new AlertDialog.Builder(requireActivity()).setTitle("清空数据").
                        setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                presenterIntf.clearDate();
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).create().show();
                break;
            case R.id.switchViewType:
                SharedPreferences sharedPreferences=requireActivity().getSharedPreferences(VIEW_TYPE_SHP, Context.MODE_PRIVATE);
                boolean isUserCardView= sharedPreferences.getBoolean(IS_USING_CARD_VIEW,false);
                SharedPreferences.Editor editor=sharedPreferences.edit();
                if(isUserCardView){
                    recyclerView.setAdapter(myadapter);
                    recyclerView.addItemDecoration(dividerItemDecoration);
                    editor.putBoolean(IS_USING_CARD_VIEW,false);}
                else {
                    recyclerView.setAdapter(myadapterUseCard);
                    recyclerView.removeItemDecoration(dividerItemDecoration);
                    editor.putBoolean(IS_USING_CARD_VIEW,true);
                }
                editor.apply();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.my_menu, menu);
        SearchView search=(SearchView)menu.findItem(R.id.app_bar_search).getActionView();
        search.setMaxWidth(700);
        search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                String patten = newText.trim();
                filteredWords.removeObservers(requireActivity());
                filteredWords = presenterIntf.findWordsWithPatten(patten);
                filteredWords.observe(getViewLifecycleOwner(), new Observer<List<Word>>() {
                    @Override
                    public void onChanged(List<Word> words) {
                        int temp = myadapter.getItemCount();
                        allWords=words;
                        if (temp != words.size()) {
                          myadapter.submitList(words);
                          myadapterUseCard.submitList(words);
                        }
                    }
                });
                return false;
            }
        });
    }

    public WordsFragment() {
        setHasOptionsMenu(true);
    }
    @Override
    public void onResume() {
        InputMethodManager inputMethodManager=(InputMethodManager)requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager.isActive())
        inputMethodManager.hideSoftInputFromWindow(getView().getWindowToken(),0);
        super.onResume();
    }
}
